// createRouter：创建router实例对象
// createWebHistory：创建history模式的路由

import { createRouter, createWebHistory } from 'vue-router'
import {parseStrEmpty} from '@/util/common'
import { useUserStore } from '@/stores/user'
import Layout from '@/views/layout/index.vue'
import Home from '@/views/home/index.vue'
import Category from '@/views/category/index.vue'
import detail from '@/views/detail/index.vue'
import CartList from '@/views/CartList/index.vue'
import Checkout from '@/views/Checkout/index.vue'
import Pay from '@/views/Pay/index.vue'
import PayBack from '@/views/Pay/PayBack.vue'
import Search from '@/views/search/index.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // path和component对应关系的位置
  routes: [
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '',
          component: Home
        },
        {
          path: 'category/:id',
          component: Category
        },
        {
          path: 'detail/:id',
          component: detail
        },
        {
          path: 'cartlist',
          component: CartList
        },
        {
          path: 'checkout',
          component: Checkout
        },
        {
          path: 'pay',
          component: Pay
        },
        {
          path: 'payCallBack',
          component: PayBack
        },
        {
          path: 'search/:keyword',
          component: Search
        },
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/404.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    }

  ],
  scrollBehavior () {
    return { top: 0 }
  }
})


// 添加路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  // 检查用户是否已登录
  const isUserLoggedIn = () => {

     return parseStrEmpty(userStore.userInfo.token) !== '';
  };

  // 如果用户已登录且尝试访问登录页面，则重定向到主页
  if (to.path === '/login' && isUserLoggedIn()) {
    next('/');
  }
  // 如果目标路由需要认证且用户未登录，则重定向到登录页面
  else if (to.path === '/payCallback' && from.path !== '/pay') {
    next('/');
  }else if (to.path === '/pay' && from.path !== '/checkout') {
    next('/');
  }
  else if (to.path === '/checkout' && from.path !== '/cartList') {
    next('/');
  }
  else if(to.path === '/cartList' && !isUserLoggedIn()){
    next('/')
  }
  else {
    next();
  }
});

export default router
